import { SiweMessage } from 'siwe';
import { ref, readonly } from 'vue';
import { useNetwork } from 'vagmi';
import type { Ref } from 'vue';

interface UseSiweMessageParams {
  address: string;
  statement: string;
  nonce: string;
}

export function useSiweMessage(params: UseSiweMessageParams) {
  const { address, statement, nonce } = params;
  const message = ref('');
  const domain = window.location.host;
  const origin = window.location.origin;
  const { chain } = useNetwork();
  const sm = new SiweMessage({
    domain,
    address,
    statement,
    nonce,
    uri: origin,
    version: '1',
    chainId: chain?.value?.id ?? 1,
  });
  message.value = sm.prepareMessage();
  return {
    message: readonly(message),
  };
}

interface UseSiweMessageValidatorParams {
  address?: Ref<string>;
  message: Ref<string>;
  signature: Ref<string | undefined>;
  nonce: Ref<string>;
}
export function useSiweMessageValidator(params: UseSiweMessageValidatorParams) {
  const { message, signature, nonce } = params;
  const isValid = ref(false);

  async function execute() {
    const sm = new SiweMessage(message.value);
    const fields = await sm.validate(signature.value);

    // 校验 nonce
    if (fields.nonce !== nonce.value) {
      isValid.value = false;
    } else {
      isValid.value = true;
    }
  }

  return {
    execute,
    isValid: readonly(isValid),
  };
}
